//7bit.cpp
#include "7bit.h"

int Encode7Bit(const U8 *pu8_In,int iLen,U8 *pu8_Out)
{
	int i,iRead,iLenOut;
	U8 u8_ReadAry[2];

	iLenOut=iLen*7/8;
	for(i=0;i<iLenOut;i++)
	{
		iRead=i+i/7;
		u8_ReadAry[0] = (pu8_In[iRead]&0x7F)>>(i%7);
		u8_ReadAry[1] = pu8_In[iRead+1]<<(7-(i%7));
		pu8_Out[i] = u8_ReadAry[0]|u8_ReadAry[1];
	}
	if(iLen%8)
	{
		pu8_Out[iLenOut] = (pu8_In[iLen-1]&0x7F)>>(iLen%8-1);
	}

	return 0;
}

int Decode7Bit(const U8 *pu8_In,int iLen,U8 *pu8_Out)
{
	int i,iRead,iLenOut,iRem;
	U8 u8_ReadAry[2];

	iLenOut=iLen+iLen/7;
	if(iLen%7) iLenOut--;
	for(i=0;i<iLenOut;i++)
	{
		iRem=i%8;
		if(iRem==0)
		{
			iRead=i-i/8;
			pu8_Out[i]=pu8_In[iRead]&0x7F;
		}
		else if(iRem==7)
		{
			iRead=i-i/8-1;
			pu8_Out[i]=pu8_In[iRead]>>1;
		}
		else
		{
			iRead=i-i/8-1;
			u8_ReadAry[0] = pu8_In[iRead]>>(8-iRem);
			u8_ReadAry[1] = (pu8_In[iRead+1]<<iRem)&0x7F;
			pu8_Out[i] = u8_ReadAry[0]|u8_ReadAry[1];
		}
	}
	iRem=iLen%7;
	if(iRem==1)
	{
		pu8_Out[iLenOut]=pu8_In[iLen-1]&0x7F;
	}
	else if(iRem>1)
	{
		u8_ReadAry[1] = (pu8_In[iLen-1]<<(iRem-1))&0x7F;
		u8_ReadAry[0] = pu8_In[iLen-2]>>(9-iRem);
		pu8_Out[iLenOut] = u8_ReadAry[0]|u8_ReadAry[1];
	}

	return 0;
}